package com.wzq.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * api 抽象控制器类，所有的controller都要继承它
 * 
 */
public class AbstractApiController {
	protected final Logger logger = LogManager.getLogger(getClass());

	/**
	 * 时间转换
	 * 
	 * @param binder
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
	}


	@SuppressWarnings("rawtypes")
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ApiResponse handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		logger.warn("api异常: {}", request.getRequestURI(), ex);

		Integer httpCode = null;
		ApiResponse apiResponse = new ApiResponse();
		if (ex instanceof ApiException) {
			ApiError error = ((ApiException) ex).getError();
			apiResponse.setCode(error.getCode());

			String msg = error.getMsg();
			if (msg != null && (msg.indexOf("Exception") != -1 || msg.indexOf("SQL") != -1)) {
				msg = ":( 亲，虫虫出现，我们的攻城狮正在抓捕!";
			}
			apiResponse.setDesc(msg);

			httpCode = error.getHttpCode();
		} else if (ex instanceof IllegalArgumentException || ex instanceof MissingServletRequestParameterException) {
			apiResponse.setDesc(ex.getMessage());
			httpCode = 400;
		}
		if (httpCode == null)
			httpCode = 500;
		if (apiResponse.getCode() == null || apiResponse.getCode().isEmpty())
			apiResponse.setCode(httpCode.toString());
		if (apiResponse.getDesc() == null)
			apiResponse.setDesc(ResponseCode.ERR.getMessage());
		response.setStatus(200);
		return apiResponse;
	}

	public Integer getParaToInt(String value, int defaultValue) {
		if (value == null || "".equals(value.trim()))
			return defaultValue;
		if (value.startsWith("N") || value.startsWith("n"))
			return -Integer.parseInt(value.substring(1));
		return Integer.parseInt(value);
	}
}
